package com.centriole.service.workflow.common;

import java.util.LinkedHashMap;
import java.util.Map;

public class LruCache<K,V> {

    private LinkedHashMap<K,V> map;
    private int limit =DEFAULT_LIMIT;

    private static final int DEFAULT_LIMIT = 16;

    public LruCache(){
        this(DEFAULT_LIMIT);
    }

    public LruCache(int limit) {
        this.limit = limit;
        int size = limit+ 1;
      //  System.err.println("当前初始化Cache大小为: " + limit);
        map = new LinkedHashMap<K,V>(size,1.0f,true){
            @Override
            protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
                boolean remove;
                if( remove = size() > limit ){
                    System.out.println( "删除了一个过期元素 [ "+eldest.getKey() + " : " + eldest.getValue() +" ]");
                }
                return remove;
            }
        };
    }

    public V put(K key, V value){
        return map.put(key,value);
    }

    public V get(K key){
        return map.get(key);
    }


    public static void main(String[] args) {
        LruCache<Integer , String> cache = new LruCache<>();
        cache.put( 1,"A" );
        cache.put(2,"B");
        cache.put(3,"C");
        cache.get(1);
        cache.put(4,"D");
        cache.put(5,"E");

    }

}
